const uuid = require('uuid/v4')
const dgram = require('dgram')
// const commonUtil = require('../renderer/util/commonUtil')

let messageListener = (msg) => {
  console.log('收到了消息', msg)
}

let server = dgram.createSocket({
  type: 'udp4',
  recvBufferSize: 65536,
  sendBufferSize: 65536
})

server.on('error', (err) => {
  console.log(`服务器异常：\n${err.stack}`)
  messageListener({
    ip: 0,
    data: JSON.stringify({action: 'error', data: err})
  })
  server.close()
})

let msgList = {}
server.on('message', (msg, rinfo) => {
  let msgJson = JSON.parse(msg.toString())
  // console.log(msgJson)
  if (!msgList[msgJson.id]) msgList[msgJson.id] = new Array(msgJson.count)
  msgList[msgJson.id][msgJson.index] = Buffer.from(msgJson.data)
  let end = true
  for (let i = 0; i < msgJson.count; i++) {
    if (!msgList[msgJson.id][i]) {
      end = false
      break
    }
  }
  if (end) {
    const m = Buffer.concat(msgList[msgJson.id])
    delete msgList[msgJson.id]
    // Vue.prototype.$eventBus.$emit('udpMsg', {
    //   ip: rinfo.address,
    //   data: m.toString()
    // })
    messageListener({
      ip: rinfo.address,
      data: m.toString()
    })
  }
})

server.on('listening', () => {
  const address = server.address()
  console.log(`服务器监听 ${address.address}:${address.port}`)
  messageListener({
    ip: 0,
    data: JSON.stringify({action: 'listening'})
  })
})

export async function udpSend (message, address = 'localhost') {
  let msg = Buffer.from(message)
  let len = msg.length
  let size = 128 // 8192
  let count = Math.ceil(len / size)
  let sendData
  let id = uuid()
  for (let i = 0; i < count; i++) {
    let end = (i + 1) * size
    if (end > len) end = len
    sendData = Buffer.from(JSON.stringify({
      id: id,
      index: i,
      count: count,
      data: msg.slice(i * size, end)
    }))
    await new Promise((resolve, reject) => {
      server.send(sendData, server.address().port, address, (err, bytes) => {
        if (err) throw err
        setTimeout(() => {
          resolve()
        }, 0)
      })
    })
  }
}

export function onMessage (msgListener) {
  messageListener = msgListener
}

export function start (port = 41234) {
  server.bind(port)
}
